package com.dwx.gmall.product.component;

import com.dwx.gmall.product.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioConfig minioConfig;

    public String upload(InputStream inputStream,String bucketName,String fileName)throws Exception{
        if(StringUtils.isEmpty(bucketName)){
            bucketName=minioConfig.getDefaultBucket();
        }else {
            if(!minioClient.bucketExists(bucketName)){
                minioClient.makeBucket(bucketName);
            }
        }
        fileName= UUID.randomUUID().toString().replace("-","")+"_"+fileName;
        PutObjectOptions options=new PutObjectOptions(inputStream.available(),-1);
        minioClient.putObject(bucketName,fileName,inputStream,options);

        String url="";
        url=minioConfig.getUrl()+"/"+bucketName+"/"+fileName;
        return url;
    }
}
